package com.serve.oa.controller;


import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.serve.oa.common.lang.Const;
import com.serve.oa.common.lang.Result;
import com.serve.oa.dto.UserAddRegDto;
import com.serve.oa.dto.UserDto;
import com.serve.oa.entity.SysUser;
import com.serve.oa.jwt.JwtUtil;
import com.serve.oa.service.SysUserService;
import com.wf.captcha.SpecCaptcha;
import com.wf.captcha.base.Captcha;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.ServletRequestUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Mono;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.concurrent.TimeUnit;

@Api(tags = "登录模块")
@RestController
@RequestMapping("/open")

public class LoginController extends BaseController {

    @Value("${custom.jwt.expire_time}")
    private long expireTime;
    private int useid = 1;

    @Autowired
    SysUserService sysUserService;
    @Autowired
    RabbitTemplate rabbitTemplate;


    @GetMapping("/captcha")
    public void generateCaptcha(HttpServletRequest request, HttpServletResponse response) throws IOException {
        SpecCaptcha specCaptcha = new SpecCaptcha(130, 48, 4);
        specCaptcha.setCharType(Captcha.TYPE_ONLY_NUMBER);

        // 将验证码文本保存在session中
        request.getSession().setAttribute("captcha", specCaptcha.text());

        // 将验证码写入响应
        response.setContentType("image/jpeg");
        specCaptcha.out(response.getOutputStream());
    }

    @ApiOperation(value = "登录")
    @PostMapping("/login")
    public Result login(@Validated @RequestBody UserDto userDto , HttpServletRequest request){


        // String captchaFromSession = (String) request.getSession().getAttribute("captcha");
        // if (captchaFromSession == null || !captchaFromSession.equals(userDto.getCode())) {
        //     return Result.fail(400,"code 错误");
        // }


        SysUser user =  sysUserService.getOne(new QueryWrapper<SysUser>().eq("username",userDto.getName()));
      //  //System.out.println(SecureUtil.md5(userDto.getPassWord()));
        if(user==null || !user.getPassword().equals(SecureUtil.md5(userDto.getPassWord()))){
            return Result.fail(400,"账号/密码错误！");
        }



        String token = JwtUtil.sign(userDto.getName(), "123");
        redisTemplate.opsForValue().set("TOKEN:"+userDto.getName(),token, expireTime*2/100, TimeUnit.SECONDS);
        return Result.succ(token);

    }

    // 测试高并发
    @ApiOperation(value = "testgbf")
    @GetMapping("/testgbf")
    public Result testGbf() throws InterruptedException {


        boolean ds =   sysUserService.qd();
        if(ds){
            return   Result.succ(200,"成功",1);
        }else {
            return  Result.fail(401,"失败");
        }





    }


    @ApiOperation(value = "test")
    @GetMapping("/test")
    public Result test() throws InterruptedException {



       String ss = String.valueOf(ServletRequestUtils.getIntParameter(req, "user", 1));


        rabbitTemplate.convertAndSend("reg007",ss);


        return Result.succ("1");



    }

    @ApiOperation(value = "注册")
    @PostMapping("/reg")
    public Result add(@Validated @RequestBody UserAddRegDto userAddDto) throws InterruptedException {

        SysUser ds =  userService.getOne(new QueryWrapper<SysUser>().eq("username",userAddDto.getUsername()));

        if(ds==null){
            SysUser user = new SysUser();
            user.setCreated(LocalDateTime.now());

            user.setCreated(LocalDateTime.now());
            user.setStatu(Const.STATUS_OFF);
            user.setCity(userAddDto.getCity());
            user.setEmail(userAddDto.getEmail());

            // 默认密码
            String password = SecureUtil.md5(userAddDto.getPassword());
            user.setPassword(password);
            user.setUsername(userAddDto.getUsername());

            // 默认头像
            user.setAvatar(Const.DEFULT_AVATAR);
            userService.save(user);

            userService.sendMsg("我发送了");
            return Result.succ(user) ;


        }else {
            return Result.fail("用户存在了");
        }

    }



}
